package com.b2c.erp.controller.wms;

import com.b2c.entity.result.PagingResponse;
import com.b2c.common.utils.DateUtil;
import com.b2c.common.utils.Number2char;
import com.b2c.interfaces.erp.ErpGoodsService;
import com.b2c.interfaces.erp.ErpUserActionLogService;
import com.b2c.entity.query.ErpStockInItemQuery;
import com.b2c.entity.vo.ErpStockInFormDetailVo;
import com.b2c.entity.vo.finance.ErpStockInFormItemVo;
import com.b2c.entity.ErpStockInFormEntity;
import com.b2c.erp.DataConfigObject;
import com.b2c.entity.enums.erp.EnumGoodsStockLogType;
import com.b2c.entity.ErpStockInFormItemEntity;

import com.b2c.interfaces.wms.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

/**
 * 描述：
 * 入库管理
 *
 * @author qlp
 * @date 2019-05-29 13:50
 */
@Controller
@RequestMapping("/stock_in")
public class StockInController {
    @Autowired
    private InvoiceService invoiceService;
    @Autowired
    private StockLocationService stockLocationService;
    @Autowired
    private ErpGoodsService goodsService;
    @Autowired
    private ErpStockInCheckoutService stockInCheckoutService;
    @Autowired
    private ErpGoodsStockLogsService goodsStockLogsService;
    
    @Autowired
    private ErpStockInFormService erpStockInFormService;
    @Autowired
    private ErpUserActionLogService logService;


    /**
     * 所有入库记录
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/logs", method = RequestMethod.GET)
    public String stockInLogs(Model model, HttpServletRequest request) {
        Integer pageIndex = 1;
        Integer pageSize = DataConfigObject.getInstance().getPageSize();
        ;
        if (StringUtils.isEmpty(request.getParameter("page")) == false) {
            try {
                pageIndex = Integer.parseInt(request.getParameter("page"));
            } catch (Exception e) {
            }
        }

        Integer startTime = 0;
        Integer endTime = 0;
        String date = request.getParameter("date");
        if (StringUtils.isEmpty(date) == false) {
            //时间筛选了2020-02-07 - 2020-02-14
            String[] st = date.split(" - ");
            if (st.length > 0) {
                startTime = DateUtil.dateToStamp(st[0]);
            }
            if (st.length > 1) {
                endTime = DateUtil.dateTimeToStamp(st[1] + " 23:59:59");
            }

        }

        var result = goodsStockLogsService.getListByType(EnumGoodsStockLogType.IN, 1, 20, startTime, endTime);

        model.addAttribute("list", result.getList());
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalSize", result.getTotalSize());

        model.addAttribute("view", "cgrk");
        model.addAttribute("pView", "sj");
        model.addAttribute("ejcd", "入库");
        model.addAttribute("sjcd", "入库记录");

        return "wms/stock_in_logs_list";
    }

    /**
     * 入库单记录
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/stock_in_form_list", method = RequestMethod.GET)
    public String getStockInFrom(Model model, HttpServletRequest request) {
        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();
        if (StringUtils.isEmpty(request.getParameter("page")) == false) {
            try {
                pageIndex = Integer.parseInt(request.getParameter("page"));
            } catch (Exception e) {
            }
        }
        Integer inType = null;
        if(StringUtils.isEmpty(request.getParameter("type"))==false){
            inType = Integer.parseInt(request.getParameter("type"));
            model.addAttribute("type",inType);
        }

        String number = Optional.ofNullable(request.getParameter("billNo")).orElse("");
        model.addAttribute("billNo", number);

//        String number = Optional.ofNullable(request.getParameter("billNo")).orElse("");
//        model.addAttribute("billNo", number);

        String iid = Optional.ofNullable(request.getParameter("iid")).orElse("0");



        Integer startDate = 0;
        if(!StringUtils.isEmpty(request.getParameter("startDate"))){
            startDate=DateUtil.dateToStamp(request.getParameter("startDate"));
        }


        Integer endDate = 0;
        if(!StringUtils.isEmpty(request.getParameter("endDate"))){
            endDate=DateUtil.dateToStamp(request.getParameter("endDate"));
        }

        model.addAttribute("startDate", request.getParameter("startDate"));
        model.addAttribute("endDate", request.getParameter("endDate"));
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        PagingResponse<ErpStockInFormEntity> result = erpStockInFormService.getErpStockInList(pageIndex, pageSize,inType, number, startDate, endDate, Long.parseLong(iid));
        model.addAttribute("list", result.getList());
        model.addAttribute("totalSize", result.getTotalSize());


            model.addAttribute("view", "rkdlb");
            model.addAttribute("pView", "sj");


        return "wms/erp_stock_in_from_list";
    }


    /**
     * 采购入库(按商品)
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/purchase_in_list", method = RequestMethod.GET)
    public String stockInByPurchase(Model model, HttpServletRequest request) {
        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();
        if(ObjectUtils.isEmpty(request.getParameter("page"))==false){
            try {
                pageIndex = Integer.parseInt(request.getParameter("page"));
            } catch (Exception e) {
            }
        }

        
        String billNo = Optional.ofNullable(request.getParameter("billNo")).orElse("");
        model.addAttribute("billNo", billNo);
        String specNumber = Optional.ofNullable(request.getParameter("specNumber")).orElse("");
        model.addAttribute("specNumber", specNumber);

//        String iid = Optional.ofNullable(request.getParameter("iid")).orElse("0");


        String startDate = request.getParameter("startDate");
        model.addAttribute("startDate", startDate);
        String endDate = request.getParameter("endDate");
        model.addAttribute("endDate", endDate);
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        var result = erpStockInFormService.getErpStockInItemListByPurchase(pageIndex, pageSize, billNo, "", "",specNumber, null, null);
        model.addAttribute("list", result.getList());
        model.addAttribute("totalSize", result.getTotalSize());

        model.addAttribute("view", "cgrklog");
        model.addAttribute("pView", "cg");
        return "wms/erp_stock_in_by_purchase_list";
    }


    /**
     * 采购入库(按商品)
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/purchase_in_list_count", method = RequestMethod.GET)
    public String purchase_in_list_count(Model model, HttpServletRequest request) {
        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();
        if(ObjectUtils.isEmpty(request.getParameter("page"))==false){
            try {
                pageIndex = Integer.parseInt(request.getParameter("page"));
            } catch (Exception e) {
            }
        }


        String billNo = Optional.ofNullable(request.getParameter("billNo")).orElse("");
        model.addAttribute("billNo", billNo);
        String specNumber = Optional.ofNullable(request.getParameter("specNumber")).orElse("");
        model.addAttribute("specNumber", specNumber);

        String goodNumber = Optional.ofNullable(request.getParameter("goodNumber")).orElse("");
        model.addAttribute("goodNumber", goodNumber);

        String startDate = request.getParameter("startDate");
        model.addAttribute("startDate", startDate);
        String endDate = request.getParameter("endDate");
        model.addAttribute("endDate", endDate);
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        ErpStockInItemQuery query=new ErpStockInItemQuery();
        query.setPageIndex(pageIndex);
        query.setPageSize(pageSize);
        query.setGoodsNumber(goodNumber);
        query.setSkuNumber(specNumber);
        query.setStartTime(DateUtil.dateTimeToStamp(startDate));
        query.setEndTime(DateUtil.dateTimeToStamp(endDate));
        var result = erpStockInFormService.purchase_in_list_count(query);
        model.addAttribute("list", result.getList());
        model.addAttribute("totalSize", result.getTotalSize());

        model.addAttribute("view", "cgrktj");
        model.addAttribute("pView", "cg");
        return "erp_stock_in_by_purchase_list_count";
    }

    @RequestMapping(value = "/purchase_in_list_count_export", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public void outExport(HttpServletRequest request, HttpServletResponse response) {
        String specNumber = Optional.ofNullable(request.getParameter("specNumber")).orElse("");

        String goodNumber = Optional.ofNullable(request.getParameter("goodNumber")).orElse("");

        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        ErpStockInItemQuery query=new ErpStockInItemQuery();
        query.setGoodsNumber(goodNumber);
        query.setSkuNumber(specNumber);
        query.setStartTime(DateUtil.dateTimeToStamp(startDate));
        query.setEndTime(DateUtil.dateTimeToStamp(endDate));
        //按条件搜索
        var lists = erpStockInFormService.purchase_in_list_count_export(query);


        /***************根据店铺查询订单导出的信息*****************/
        String excelFileName = "erp_stock_inItem_list_";//excel文件名前缀
        //创建Excel工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();

        //创建Excel工作表对象
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow row = null;
        HSSFCell cell = null;
        //第一行为空
        row = sheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("ID");
        cell = row.createCell(1);
        cell.setCellValue("SKU");
        cell = row.createCell(2);
        cell.setCellValue("规格");
        cell = row.createCell(3);
        cell.setCellValue("商品款号");
        cell = row.createCell(4);
        cell.setCellValue("商品名称");
        cell = row.createCell(5);
        cell.setCellValue("入库数量");
        cell = row.createCell(6);
        cell.setCellValue("总金额");
        int currRowNum = 0;
        // 循环写入数据
        for (int i = 0; i < lists.size(); i++) {
            currRowNum++;
            //写入订单
            ErpStockInFormItemVo itemVo = lists.get(i);

            //创建行
            row = sheet.createRow(currRowNum);
            //Id
            cell = row.createCell(0);
            cell.setCellValue(itemVo.getSpecId());
            //商品名称
            cell = row.createCell(1);
            cell.setCellValue(itemVo.getSpecNumber());
            //出库单号
            cell = row.createCell(2);
            cell.setCellValue(itemVo.getColorValue()+" "+itemVo.getSizeValue());
            //退货单号
            cell = row.createCell(3);
            cell.setCellValue(itemVo.getGoodsNumber());
            //规格
            cell = row.createCell(4);
            cell.setCellValue(itemVo.getGoodsName());
            //SKU
            cell = row.createCell(5);
            cell.setCellValue(itemVo.getQuantity()+"");
            //商品款号
            cell = row.createCell(6);
            cell.setCellValue(itemVo.getPrice().doubleValue()*itemVo.getQuantity());
        }
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
            SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
            String date = newsdf.format(new Date());
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String((excelFileName + date + ".xls").getBytes("GBK"),
                    "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        }

        return;
    }


    /**
     * 采购单生产合同
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/purchase_in_ht_export", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public void purchase_in_ht_export(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Long iid= Long.parseLong(request.getParameter("id"));

        ClassPathResource classPathResource = new ClassPathResource("/export-template/purchase_contract.xls");
        InputStream inputStream =classPathResource.getInputStream();
        //按条件搜索

        /***************根据店铺查询订单导出的信息*****************/
        String excelFileName = "erp_stock_inItem_list_";//excel文件名前缀
        //创建Excel工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook(inputStream);

        //创建Excel工作表对象
        HSSFSheet sheet = workbook.getSheetAt(0);
        HSSFRow row = null;
        HSSFCell cell = null;
        var lists = erpStockInFormService.purchase_in_ht_export(iid);

        row=sheet.getRow(1);
        cell=row.getCell(8);
        cell.setCellValue("合同号:"+lists.get(0).getContractNo());

        int currRowNum = 7;

        Long totalQty=0L;

        double totalAmount=0d;

        for (int i = 0; i < lists.size(); i++) {
            currRowNum++;
            //写入订单
            ErpStockInFormItemVo itemVo = lists.get(i);
            if(currRowNum>=24){
                sheet.shiftRows(currRowNum,sheet.getLastRowNum(), 1, true, false);
                sheet.createRow(currRowNum);
                row = sheet.getRow(currRowNum);
                for(int j=0;j<11;j++){
                     row.createCell(j);
                }
                sheet.addMergedRegion(new CellRangeAddress(currRowNum,currRowNum,0,2));
                sheet.addMergedRegion(new CellRangeAddress(currRowNum,currRowNum,3,5));
            }else{
                row = sheet.getRow(currRowNum);
            }
            totalQty+=itemVo.getQuantity();
            double price=itemVo.getPrice().doubleValue()*itemVo.getQuantity();
            totalAmount+=price;
            //Id
            cell = row.getCell(0);
            cell.setCellValue(itemVo.getGoodsName());
            //商品名称
            cell = row.getCell(3);
            cell.setCellValue(itemVo.getGoodsNumber());
            //出库单号
            cell = row.getCell(6);
            cell.setCellValue(itemVo.getUnitName());
            //退货单号
            cell = row.getCell(7);
            cell.setCellValue(itemVo.getQuantity());
            //规格
            cell = row.getCell(8);
            cell.setCellValue("¥"+itemVo.getPrice());
            //SKU
            cell = row.getCell(9);
            cell.setCellValue("¥"+price);
            //商品款号
            cell = row.getCell(10);
            cell.setCellValue(itemVo.getColorValue()+itemVo.getQuantity()+"件");
        }
        if(currRowNum<24)currRowNum=23;
        row = sheet.getRow(currRowNum+1);
        cell = row.getCell(7);
        cell.setCellValue(totalQty);

        row = sheet.getRow(currRowNum+2);
        cell=row.getCell(2);
        cell.setCellValue(Number2char.toChineseChar(totalAmount));

        cell = row.getCell(9);
        cell.setCellValue(new BigDecimal(totalAmount).setScale(2,RoundingMode.HALF_UP)+"");
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
            SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
            String date = newsdf.format(new Date());
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String((excelFileName + date + ".xls").getBytes("GBK"),
                    "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        }

        return;
    }


    /**
     * 入库单详情（打印，弹窗）
     *
     * @param model
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "/form_item", method = RequestMethod.GET)
    public String stock_in_form(Model model, @RequestParam Long id, HttpServletRequest request) {
        var detail = erpStockInFormService.getById(id);

        if (detail != null) {
            model.addAttribute("detail", detail);

        } else {
            model.addAttribute("detail", new ErpStockInFormDetailVo());
        }

        return "erp_stock_in_form_item";
    }

    /**
     * 导出入库单（按入库单id）
     * @param request
     * @param response
     */
    @RequestMapping(value = "/form_item_export", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public void outExportFormItem(HttpServletRequest request,@RequestParam Long id, HttpServletResponse response) {
        var stockInForm = erpStockInFormService.getById(id);

        if (stockInForm == null) {
            //数据为null，导出失败
            return;
        }


        /***************根据店铺查询订单导出的信息*****************/
        String excelFileName = "erp_stock_in_form_item_";//excel文件名前缀
        //创建Excel工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();

        //创建Excel工作表对象
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow row = null;
        HSSFCell cell = null;
        //第一行为空
        row = sheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("入库单ID");
        cell = row.createCell(1);
        cell.setCellValue("入库单编号");
        cell = row.createCell(2);
        cell.setCellValue("SKU");
        cell = row.createCell(3);
        cell.setCellValue("规格");
        cell = row.createCell(4);
        cell.setCellValue("商品款号");
        cell = row.createCell(5);
        cell.setCellValue("商品名称");
        cell = row.createCell(6);
        cell.setCellValue("入库数量");
        cell = row.createCell(7);
        cell.setCellValue("入库仓位");
        cell = row.createCell(8);
        cell.setCellValue("入库时间");
        int currRowNum = 0;
        // 循环写入数据
        for (int i = 0; i < stockInForm.getItems().size(); i++) {
            currRowNum++;
            //写入订单
            ErpStockInFormItemEntity itemVo = stockInForm.getItems().get(i);

            //创建行
            row = sheet.createRow(currRowNum);
            //Id
            cell = row.createCell(0);
            cell.setCellValue(stockInForm.getId());
            cell = row.createCell(1);
            cell.setCellValue(stockInForm.getNumber());
            //商品名称
            cell = row.createCell(2);
            cell.setCellValue(itemVo.getSpecNumber());
            //出库单号
            cell = row.createCell(3);
            cell.setCellValue(itemVo.getColorValue()+" "+itemVo.getSizeValue());
            //退货单号
            cell = row.createCell(4);
            cell.setCellValue(itemVo.getGoodsNumber());
            //规格
            cell = row.createCell(5);
            cell.setCellValue(itemVo.getGoodsName());
            //SKU
            cell = row.createCell(6);
            cell.setCellValue(itemVo.getQuantity()+"");
            //入库仓位
            cell = row.createCell(7);
            cell.setCellValue(itemVo.getLocationNumber());
            //入库时间
            cell = row.createCell(8);
            cell.setCellValue(DateUtil.stampToDateTime(stockInForm.getStockInTime1()));
        }
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
//            SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
//            String date = newsdf.format(new Date());
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String((excelFileName + stockInForm.getNumber() + ".xls").getBytes("GBK"),
                    "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        }

        return;
    }
}
